package com.forward.uploadapp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.forward.uploadapp.BaseActivity;
import com.forward.uploadapp.R;
import com.forward.uploadapp.adapter.GetJsonAdapter;
import com.forward.uploadapp.dialog.OnWarnDialogListener;
import com.forward.uploadapp.dialog.WarmDialog;
import com.forward.uploadapp.entity.AppInfo;
import com.forward.uploadapp.entity.AppLayout;
import com.forward.uploadapp.entity.JsonAllParse;
import com.forward.uploadapp.util.BmobUtils;
import com.forward.uploadapp.util.FileHelper;
import com.forward.uploadapp.util.ToastUtils;
import com.forward.uploadapp.util.ToolUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

public class BmobActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    private List<AppInfo> mDatas;
    private GetJsonAdapter mAdapter;
    private ListView mListView;
    private Map<String, List<AppInfo>> mMap;
    private AppInfo mSelectAppInfo;
    private View mLastView;

    @Override
    public int getLayoutId() {
        return R.layout.activity_bmob;
    }

    @Override
    public void initView() {
        mListView = (ListView) findViewById(R.id.listview);
    }

    @Override
    public void initData() {
        mMap = new HashMap<>();
        mDatas = new ArrayList<>();
        mAdapter = new GetJsonAdapter(this, mDatas);
        mListView.setAdapter(mAdapter);
        refresh();
    }

    @Override
    public void initListener() {
        mListView.setOnItemClickListener(this);
    }

    private void refresh() {
        refresh(true);
    }

    private void refresh(boolean isRequest) {
        mSelectAppInfo = null;
        if (mLastView != null) {
            mLastView.setSelected(false);
            mLastView = null;
        }
        if (isRequest) {
            BmobUtils.queryAllAppInfoData(new FindListener<AppInfo>() {
                @Override
                public void done(List<AppInfo> list, BmobException e) {
                    if (e == null) {
                        mDatas.clear();
                        mDatas.addAll(list);
                        mAdapter.refresh();
                        ToastUtils.toast(BmobActivity.this, getString(R.string.refresh_success));
                    } else {
                        ToastUtils.toast(BmobActivity.this, getString(R.string.get_data__fail));
                    }
                }
            });
        } else {
            mAdapter.refresh();
        }
    }

    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.add:
                intent = new Intent(this, AppInfoActivity.class);
                intent.putExtra("from", FROM_BMOB_ACTIVITY);
                startActivityForResult(intent, FROM_BMOB_ACTIVITY);
                break;
            case R.id.refresh:
                refresh();
                break;
            case R.id.edit:
                if (mSelectAppInfo != null) {
                    intent = new Intent(BmobActivity.this, AppInfoActivity.class);
                    intent.putExtra("appInfo", mSelectAppInfo);
                    intent.putExtra("from", FROM_BMOB_ACTIVITY);
                    startActivityForResult(intent, FROM_BMOB_ACTIVITY);
                } else {
                    ToastUtils.toast(BmobActivity.this, getString(R.string.no_target));
                }
                break;
            case R.id.remove:
                removeApp();
                break;
        }
    }

    private void removeApp() {
        if (mSelectAppInfo != null) {
            WarmDialog.getInstance(this).showDialog(
                    "确定删除" + mSelectAppInfo.getAppName(), new OnWarnDialogListener() {
                        @Override
                        public void cancel(Dialog dialog) {
                            dialog.dismiss();
                        }

                        @Override
                        public void confirm(Dialog dialog) {
                            BmobUtils.deleteData(mSelectAppInfo, new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        ToastUtils.toast(
                                                BmobActivity.this,
                                                getString(R.string.remove_success));
                                        mDatas.remove(mSelectAppInfo);
                                        refresh(false);
                                    } else {
                                        ToastUtils.toast(
                                                BmobActivity.this,
                                                getString(R.string.remove_fail));
                                    }
                                }
                            });
                            dialog.dismiss();
                        }
                    });
        } else {
            ToastUtils.toast(BmobActivity.this, getString(R.string.no_target));
        }
    }

    public void output(View view) {
        Collections.sort(mDatas, new Comparator<AppInfo>() {
            @Override
            public int compare(AppInfo o1, AppInfo o2) {
                return ToolUtils.transformTimeLong(o1.getUpdatedAt())
                        < ToolUtils.transformTimeLong(o2.getUpdatedAt()) ? 1 : -1;
            }
        });
        if (mDatas == null) {
            ToastUtils.toast(this, getString(R.string.please_get_all_json_data));
            return;
        }
        boolean isOutput = false;
        JsonAllParse jsonAllParse = new JsonAllParse();
        jsonAllParse.setInfos(mDatas);
        FileHelper.mkAppDir("/download");
        FileHelper.mkAppDir("/icon");
        isOutput = FileHelper.writeFile(new JsonAllParse(mDatas).toString(), "/all");
        isOutput = isOutput && FileHelper.writeFile(output(OUTPUT_SOFTWARE), "/data/software");
        isOutput = isOutput && FileHelper.writeFile(output(OUTPUT_HOME), "/data/home");
        isOutput = isOutput && FileHelper.writeFile(output(OUTPUT_GAME), "/data/game");
        ToastUtils.toast(this, getString(isOutput ? R.string.output_success : R.string.output_fail));
    }

    public String output(int type) {
        sortDatas();
        AppLayout appLayout = new AppLayout();
        appLayout.setResult(200);
        appLayout.setMessage("OK");
        List<AppLayout.AppLayoutInfo> appLayoutInfos = new ArrayList<>();
        appLayout.setAppLayoutInfos(appLayoutInfos);
        AppLayout.AppLayoutInfo appLayoutInfo;
        List<AppInfo> appInfos;
        switch (type) {
            case OUTPUT_GAME:
                appInfos = mMap.get(getString(R.string.game));
                appLayoutInfo = new AppLayout.AppLayoutInfo();
                appLayoutInfo.setType(getString(R.string.game));
                appLayoutInfo.setWhole(getString(R.string.whole));
                appLayoutInfo.setAppInfos(appInfos);
                appLayout.getAppLayoutInfos().add(appLayoutInfo);
                break;
            case OUTPUT_SOFTWARE:
                appLayoutInfo = new AppLayout.AppLayoutInfo();
                String all = getString(R.string.all);
                appLayoutInfo.setType(all);
                appLayoutInfo.setWhole(getString(R.string.whole));
                appLayoutInfo.setAppInfos(mMap.get(all));
                appLayout.getAppLayoutInfos().add(appLayoutInfo);

                for (String mapType : mMap.keySet()) {
                    if (mapType.equals(getString(R.string.game)) || mapType.equals(all)) {
                        continue;
                    }
                    appLayoutInfo = new AppLayout.AppLayoutInfo();
                    appLayoutInfo.setType(mapType);
                    appLayoutInfo.setWhole(getString(R.string.whole));
                    appLayoutInfo.setAppInfos(mMap.get(mapType));
                    appLayout.getAppLayoutInfos().add(appLayoutInfo);
                }

                break;
            case OUTPUT_HOME:
                for (int i = 0; i < 3; i++) {
                    appLayoutInfo = new AppLayout.AppLayoutInfo();
                    appLayoutInfo.setWhole(getString(R.string.whole));
                    appInfos = new ArrayList<>();
                    switch (i) {
                        case 0:
                            appLayoutInfo.setType("最新推荐");
                            appInfos.addAll(mDatas.subList(0, Math.min(mDatas.size(), 10)));
                            break;
                        case 1:
                            appLayoutInfo.setType("最受欢迎");
//                            appInfos.addAll(mMap.get("图像影音").subList(0, Math.min(mDatas.size(), 3)));
//                            appInfos.addAll(mMap.get("网络社交").subList(0, Math.min(mDatas.size(), 4)));
                            appInfos.addAll(mDatas.subList(11, Math.min(mDatas.size(), 20)));

                            break;
                        case 2:
                            appLayoutInfo.setType("最受好评");
//                            appInfos.addAll(mMap.get("应用工具").subList(0, Math.min(mDatas.size(), 3)));
//                            appInfos.addAll(mMap.get("游戏").subList(0, Math.min(mDatas.size(), 5)));
                            appInfos.addAll(mDatas.subList(21, Math.min(mDatas.size(), 30)));

                            break;
                    }
                    appLayoutInfo.setAppInfos(appInfos);
                    appLayout.getAppLayoutInfos().add(appLayoutInfo);
                }
                break;
        }
        return appLayout.toString();
    }

    private void sortDatas() {
        mMap.clear();
        if (!mMap.containsKey(getString(R.string.all))) {
            mMap.put(getString(R.string.all), new ArrayList<AppInfo>());
        }
        for (int i = 0; i < mDatas.size(); i++) {
            AppInfo appInfo = mDatas.get(i);
            String type = appInfo.getType();

            if (!appInfo.getType().equals(getString(R.string.game))) {
                mMap.get(getString(R.string.all)).add(appInfo);
            }
            if (mMap.containsKey(type)) {
                mMap.get(type).add(mDatas.get(i));
            } else {
                mMap.put(type, new ArrayList<AppInfo>());
                mMap.get(type).add(mDatas.get(i));
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mLastView == null) {
            view.setSelected(true);
            mSelectAppInfo = mDatas.get(position);
            mLastView = view;
        } else if (mLastView == view) {
            mLastView.setSelected(false);
            view.setSelected(false);
            mSelectAppInfo = null;
            mLastView = null
            ;
        } else {
            mLastView.setSelected(false);
            view.setSelected(true);
            mSelectAppInfo = mDatas.get(position);
            mLastView = view;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FROM_BMOB_ACTIVITY && resultCode == FROM_APP_INFO_ACTIVITY) {
            refresh();
        }
    }

    @Override
    public void onBackPressed() {

    }
}
